package main

import (
	"acs/comet"
	"acs/comet/client"
	"acs/comet/config"
	"acs/comet/servernode"
	"acs/taskprocess"
	"net/http"
	_ "net/http/pprof"
	"sync"
	"syscall"

	log "github.com/cihub/seelog"
)

// exitWG 等待所有工作协程正常退出
var exitWG = &sync.WaitGroup{}

func init() {
	config.Conf = config.InitConfig()
}

func main() {
	// pprof
	go http.ListenAndServe(":7111", nil)
	logger, err := log.LoggerFromConfigAsString(`<seelog levels="` + config.Conf.LogLevels + `">
    <outputs formatid="common">
        <console />
    </outputs>
    <formats>
    <format id="common" format="[%Level]%Date(2006/01/02 15:04:05.999)[%File:%Line] %Msg%n"/>
</formats>
</seelog>
	`)
	if err != nil {
		panic(err)
	}
	err = log.ReplaceLogger(logger)
	if err != nil {
		panic(err)
	}
	defer log.Flush()

	comet.SetLogger(logger)
	taskprocess.SetLogger(logger)
	client.SetLogger(logger)
	clientList := client.NewClientList(config.Conf.ClientListShard)
	taskprocess.SetClientManager(clientList)
	taskMonitor, err := taskprocess.NewTaskMonitor(
		taskprocess.Config{
			QueueLookupdAddrs: config.Conf.TaskServerQueueServerLookupd,
			TopicName:         config.Conf.TaskQueueTopic,
			ChannelName:       config.Conf.TaskQueueChannel,
			Storage:           config.Conf.StorageMgo,
		})
	if err != nil {
		log.Errorf("Task process monitor start error: %v", err)
		panic(err)
	}
	taskMonitor.SetProcessingCurrency(1)

	err = comet.StartAppConfigServer(config.Conf.AppConfServerBind, clientList, exitWG)
	if err != nil {
		log.Errorf("AppConfigServer start error: %v", err)
		panic(err)
	}

	cs, err := comet.NewControlServer(config.Conf.ControlServerBind)
	if err == nil {
		go func() {
			err = cs.Serve()
			if err != nil && err != comet.ErrorControlServerClosed {
				log.Error("ControlServer start error: ", err)
				panic(err)
			}
		}()
	}
	defer clientList.Close()

	signalChan, exitSigChan := comet.InitSignal()
	go comet.HandleSignal(signalChan)

	servernode.SetLogger(logger)
	err = servernode.RegisterNode(config.Conf.AppConfServerBind, config.Conf.EventBrokerEndpoints, config.Conf.EventBrokerAuthinfo, config.Conf.NodesMonitorDir, exitSigChan)
	if err != nil {
		log.Infof("Register node failed[%v]. exit...", err)
		signalChan <- syscall.SIGTERM
	}

	comet.WaitForExit(exitWG)
}
